package com.cat.dataStructure02;

import java.util.PriorityQueue;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/number-of-orders-in-the-backlog/
 * @create 2025/10/6 18:37
 * @since JDK17
 */

public class Solution01 {
    static int N = ((int) (1e9 + 7));
    public int getNumberOfBacklogOrders(int[][] orders) {
        PriorityQueue<int[]> sells = new PriorityQueue<>((a, b) -> a[1] - b[1]);
        PriorityQueue<int[]> buys = new PriorityQueue<>((a, b) -> b[1] - a[1]);
        long ans = 0;
        for (var x : orders) {
            if (x[2] == 0) {    // 订购
                while (!sells.isEmpty() && x[0] != 0) {
                    var y = sells.poll();
                    if (y[1] > x[1]) {  // 买不起
                        break;
                    }
                    if (x[0] > y[0]) {
                        x[0] -= y[0];
                    } else {
                        y[0] -= x[0];
                        x[0] = 0;
                        sells.add(y);
                    }
                }
                if (x[0] != 0) {
                    buys.add(x);
                }
            } else {    // 销售
                while (!buys.isEmpty() && x[0] != 0) {
                    var y = buys.poll();
                    if (y[1] < x[1]) {  // 买不起
                        break;
                    }
                    if (x[0] > y[0]) {
                        x[0] -= y[0];
                    } else {
                        y[0] -= x[0];
                        x[0] = 0;
                        sells.add(y);
                    }
                }
                if (x[0] != 0) {
                    sells.add(x);
                }
            }
        }
        while (!sells.isEmpty()) {
            int x = sells.poll()[0];
            ans = (ans + x) % N;
        }

        while (!buys.isEmpty()) {
            int x = buys.poll()[0];
            ans = (ans + x) % N;
        }
        return ((int) ans);
    }
}
